<template>
  <!-- 人员列表（带悬浮框） -->
  <!-- 功能：懒加载、懒加载状态、可搜索 -->
  <select-with-tooltip
    v-model="currentValue"
    v-bind="$attrs"
    show-search
    style="width: 100%"
    :filter-option="false"
    v-on="$listeners"
    :dataList="data"
    :replaceFields="{
      label: 'name',
      value: 'userId'
    }"
    :customTips="customTips"
    @popupScroll="(name, e) => handleScroll(name, e)"
    @search="handleSearch"
    @change="handleChange"
  >
    <a-icon
      v-if="fetching"
      slot="suffixIcon"
      style="color: #096dd9"
      type="loading"
    />
  </select-with-tooltip>
</template>
<script>
import debounce from 'lodash/debounce'
import { getEmployees } from '@/api/businessAffairs/revenueAndCost'
import SelectWithTooltip from '@/components/Select/SelectWithTooltip' // 带悬浮框选择器

export default {
  name: 'SelectStaffWithTooltip',
  components: {
    SelectWithTooltip
  },
  props: {
    value: {
      type: [Object, String, Array, Number]
    },
    // 请求参数
    requestParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 是否初始化
    isInit: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    // 组织id
    rootOrgId: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 不能选择自己
    notMyself: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 请求参数
    requestParams: {
      deep: true,
      handler: function (newVal) {
        if (newVal && Object.keys(newVal)?.length) {
          this.data = []
          this.pageNumber = 1
          this.handleEmployees()
        }
      }
    },
    // 组织id
    rootOrgId(newVal) {
      if (newVal) {
        this.data = []
        this.pageNumber = 1
        this.handleEmployees()
      }
    }
  },
  data() {
    this.lastFetchId = 0
    this.handleSearch = debounce(this.handleSearch, 800)
    return {
      data: [], // 渲染列表
      baseData: [], // 每次请求的最新列表
      fetching: false, // 请求加载loading
      noScroll: true, // 是否不滚动
      pageNumber: 1, // 页码
      totalPages: 1, // 总数
      searchVal: '', // 关键词
      // 用户信息
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info'))
    }
  },
  computed: {
    // 表单值
    currentValue: {
      get: function () {
        return this.value
      },
      set: function (e) {
        this.$emit('input', e)
        if (e && this.data?.length > 0) {
          let isLabelInValue = this.$attrs?.labelInValue // 表单值是否是对象
          let isMultiple = this.$attrs?.mode === 'multiple' // 是否多选
          let data = isMultiple ? this.data.filter((item) => (isLabelInValue ? e.map((i) => i.key) : e).includes(item.userId)) : this.data.filter((item) => item.userId === (isLabelInValue ? e.key : e))
          this.$emit('getOption', data)
        }
      }
    }
  },
  mounted() {
    /**
     * 请求人员
     * */

    this.isInit && this.handleEmployees()
  },
  methods: {
    /**
     * @description: 悬浮框自定义内容
     * @param {Object} data：选项对象
     * @return {String}
     */
    customTips(data) {
      if (data.postPNames?.length > 10) {
        data.postPNames?.splice(9, 10)
      }
      let jobNum = data.jobNum && data.phone ? data.jobNum + '，' : data.jobNum || '' // 员工编号
      let phone = data.postPNames?.length > 0 && data.phone ? data.phone + '，' : data.phone || '' // 员工电话
      let postPNames = data.postPNames?.join('，') || '' // 员工岗位列表
      return jobNum + phone + postPNames
    },
    /**
     * 模糊搜索
     */
    /**
     * @description:
     * @param {String} 关键词
     */
    handleSearch(value) {
      this.lastFetchId += 1
      this.data = []
      this.searchVal = value
      this.handleEmployees(value, 1)
    },
    /**
     * @description: 表单值改变
     */
    handleChange() {
      // 搜索重置
      this.pageNumber = 1
      this.searchVal = ''

      Object.assign(this, {
        data: this.baseData,
        fetching: false
      })
    },
    /**
     * @description: 下拉滚动加载
     * @param {Object} e：原生事件对象
     */
    handleScroll(e) {
      let that = this
      const { target } = e
      var total = target.scrollTop + target.offsetHeight
      var scrollHeight = target.scrollHeight
      // this.pageNo是当前页 this.totalPage是总页数
      if (total >= scrollHeight - 1 && total < scrollHeight + 1 && that.pageNumber <= that.totalPages && that.noScroll) {
        that.pageNumber += 1
        that.handleEmployees()
      }
      if (that.pageNumber > that.totalPages) {
        that.noScroll = false
        that.pageNumber = 1
      } else {
        that.noScroll = true
      }
    },
    /**
     * @description: 承办领导/部门负责人
     * @param {String} val：关键词
     * @param {Number} searchPageNumber：页码
     */
    handleEmployees(val, searchPageNumber) {
      this.fetching = true
      const pageNumber = searchPageNumber ? searchPageNumber : this.pageNumber
      let params = {
        pageNumber: pageNumber,
        pageSize: 10,
        nameLike: this.searchVal,
        rootOrgId: this.rootOrgId
      }
      // 添加额外参数
      if (Object.keys(this.requestParams)?.length) {
        params = Object.assign({}, params, this.requestParams)
      }
      getEmployees(params)
        .then((res) => {
          this.fetching = false
          // 关键词不存在
          if (!val) {
            this.data = this.data.concat(res.data.list)
            this.baseData = this.data
            // 关键词存在
          } else {
            const fetchId = this.lastFetchId
            if (fetchId !== this.lastFetchId) {
              // for fetch callback order
              return
            }
            this.data = res.data.list
          }
          // 不能选择自己
          if(this.notMyself){
            this.data = this.data.filter(el=>el.userId !== this.userInfo?.id)
          }
          this.totalPages = res.data.total
        })
        .catch(() => {
          this.fetching = false
        })
    }
  }
}
</script>